const jwt = require('jsonwebtoken')

// ? 生成 token 
module.exports.generateToken = (payload) => {
  return 'Bearer ' + jwt.sign(payload, 'txbb', { algorithm: 'HS256', expiresIn: 60 * 60 })
}

// ? 校验 token (中间件)
module.exports.verifyToken = (req, res, next) => {
  // 获取 token
  const token = req.headers.authorization.split(' ')[1]
  // 解析 token
  jwt.verify(token, 'txbb', (err, data) => {
    if (err) throw err
    let keys = Object.keys(data).filter(item => item != 'iat' && item != 'exp')
    keys.forEach(key => {
      req[key] = data[key]
    })
    next()
  })
}